package top.easycode.app.controller;



import org.apache.commons.io.IOUtils;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import sun.misc.BASE64Encoder;
import top.easycode.app.common.BaseResult;
import top.easycode.app.common.HeaderReq;
import top.easycode.app.constants.RespCode;
import top.easycode.app.exception.BusinessRuntimeException;
import top.easycode.app.util.DTOUtil;
import top.easycode.app.util.ValidatorUtil;

import javax.servlet.http.HttpServletRequest;
import java.io.*;


@Controller
@RequestMapping("/dispose")
public class AppController {

    private Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    APPBusinessService appBusinessService;

    /**
     * <B>方法名称：</B>dispose<BR>
     * <B>概要说明：</B>所有接口的统一入口<BR>
     */
    @RequestMapping(value = "", method = RequestMethod.POST, produces = "text/plain;charset=utf-8")
    @ResponseBody
    public String dispose(HttpServletRequest request) {
    	return dispose(request, "json");
    }
    
    /**
     * <B>方法名称：</B>dispose<BR>
     * <B>概要说明：</B>所有接口的统一入口<BR>
     */
    @RequestMapping(value = "/{type}", method = RequestMethod.POST, produces = "text/plain;charset=utf-8")
    @ResponseBody
    public String dispose(HttpServletRequest request,@PathVariable String type) {
        try {
        	if(type != null && !type.equals("xml") && !type.equals("json")){
        		log.error("请求的报文格式异常：" + type);
        		return sendErrorContext(RespCode.E_1010.getCode(), RespCode.E_1010.getName());
        	}

            return doDispose(request, type);

        }catch(BusinessRuntimeException e){
        	log.error("业务异常：" + (e.getMessage()==null ? e.getRespDesc() : e.getMessage()));
        	return sendErrorContext(e.getRespCode(), e.getRespDesc());
        }catch (Exception e) {
            log.error("系统异常: "+e.getMessage(), e);
            String msg = e.getMessage();
            if(msg.length()>100){
                msg = "系统异常，请与管理员联系";
            }
            return sendErrorContext(null,msg);
        }
    }

    //执行操作
    public String doDispose(HttpServletRequest request, String type) throws Exception {
        //获取报文
        String entryptContext = getRequestContent(request);
        if (StringUtils.isBlank(entryptContext)) {
            throw new BusinessRuntimeException(RespCode.E_1002.getCode(),RespCode.E_1002.getName());
        }
/*
        log.info("----------------密文-----------------\n" +entryptContext);
        //获取3Des解密后的密钥
        String desKey = wscSecurityService.get3DesKey(entryptContext);
        
        //解密报文
        //TODO 解密服务名要改*/
        String context = entryptContext;
        log.info("-----------------请求的报文-----------------\n" + context);
        if (StringUtils.isBlank(context)) {
        	log.error("解密后的报文为空");
            throw new BusinessRuntimeException(RespCode.E_1003.getCode(),RespCode.E_1003.getName());
        }

        //获取必要信息
        HeaderReq headerReq = DTOUtil.parseDTO(context, HeaderReq.class, type);
        
        //基础报文头参数校验
        ValidatorUtil.checkParameter(headerReq);
        
        //获取application
        String application = headerReq.getApplication();

        //业务判断处理
        BaseResult b = appBusinessService.dispose(request, application, context, type);
        //返回报文
        if (RespCode.E_0000.getCode().equals(b.getRespCode())) {
            String resultContext = b.getMsgExt();
            log.info("-------------------返回报文--------------------" + resultContext);
//            return wscSecurityService.sendEncryptContext(resultContext, desKey);
            return resultContext;
        } else {
        	log.info("-------------------返回错误信息--------------------" + b.getRespDesc());
            throw new BusinessRuntimeException(b.getRespCode(), b.getRespDesc());
        }
    }
    /**
     * 从流里面读取报文
     */
    private String getRequestContent(HttpServletRequest request) throws IOException {
        String reqContext = null;
        StringBuilder tmpBuffer = new StringBuilder("");
        InputStream is = null;
        BufferedReader reader = null;
        try {
            is = request.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is));
            String tempStr;
            while ((tempStr = reader.readLine()) != null) {
                tmpBuffer.append(tempStr);
            }
            reqContext = tmpBuffer.toString();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            throw e;
        } finally {
            IOUtils.closeQuietly(is);
            IOUtils.closeQuietly(reader);
        }
        return reqContext;
    }


	public String sendErrorContext(String code, String cause) {
    	String clientMsg = null;
    	log.error("错误编号：" + code + ", 错误信息：" + cause+",反馈给客户端:"+clientMsg);
    	cause = StringUtils.isEmpty(clientMsg) ? cause : clientMsg;
    	try {
    		return "0|" + (code==null ? "1002" : code) + "|" + (new BASE64Encoder().encodeBuffer(cause==null ? "未知错误".getBytes("utf-8") : cause.getBytes("utf-8")));
		} catch (UnsupportedEncodingException e) {
			log.error("系统错误"+e.getMessage(), e);
		}
		return null;
    }

}
